package com.guaoran.distributed.io.nio.two.server;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @Author gucheng
 * @Description 编解码工具类
 * 2019-04-29 17:29
 */
public class CodecUtil {
    public static ByteBuffer read(SocketChannel channel){
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            int count = channel.read(buffer);
            if(count<0){
                return null;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return buffer;
    }

    public static void write (SocketChannel channel,String content){
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            buffer.put(content.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        buffer.flip();
        try {
            // 不考虑写入超过 Channel 缓存区上限。
            channel.write(buffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String newStr(ByteBuffer byteBuffer){
        byteBuffer.flip();
        byte[] bytes = new byte[byteBuffer.remaining()];
        System.arraycopy(byteBuffer.array(),byteBuffer.position(),bytes,0,byteBuffer.remaining());
        try {
            return new String(bytes,"utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
